package vn.vfriends.soffice.bean;

import java.io.IOException;
import java.io.Serializable;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author chaungoctuan@gmail.com
 */
@Named
@RequestScoped
public class SecurityBean implements Serializable {

    private Logger logger = LoggerFactory.getLogger(SecurityBean.class);
    
    private String username;
    
    private String password;
    
    private static final String HOME_URL = "/index.jsf";
    
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    public void loginAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            HttpServletRequest hReq = (HttpServletRequest)context.getExternalContext().getRequest();
            SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password));
            SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(hReq);
            context.getExternalContext()
                    .redirect(savedRequest != null ? savedRequest.getRequestUrl() : hReq.getContextPath() + HOME_URL);
        } catch (AuthenticationException | IOException ex) {
            logger.error(ex.getMessage(), ex);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Login failed", ""));
        }
    }
    
    public void logoutAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try{
            SecurityUtils.getSubject().logout();
            context.getExternalContext().invalidateSession();
            HttpServletRequest hReq = (HttpServletRequest)context.getExternalContext().getRequest();
            context.getExternalContext().redirect(hReq.getContextPath() + HOME_URL);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
    }
    
    public boolean hasPermission(String permission) {
        return SecurityUtils.getSubject().isPermitted(new WildcardPermission(permission));
    }
}
